<template>
  <div style="box_wrap">
    <!-- 头部定位 -->
    <div class="header">
      <div class="header_left" @click="getCity">
        <img src="../assets/ic_XY.png" alt />
        <div>当前位置: {{city||'重新定位'}}</div>
      </div>
      <div class="header_right warp">
        <div>敏感词过滤：</div>
        <group>
          <x-switch title=" " value="isFil" v-model="isFil"></x-switch>
        </group>
      </div>
    </div>
    <!-- 删除 -->
    <div class="del_warp">
      <div>聊天记录</div>
      <img src="../assets/ic_del.png" alt @click="deleteList" />
    </div>
    <!-- list -->
    <div class="list_wrap">
      <div class="noList" v-if="findList.length==0">
        <img src="../assets/ic_noTalking.png" alt />
        <div>还没有消息哦,快去聊天吧~</div>
      </div>
      <div
        class="list_item"
        v-else
        @click="goChat(index)"
        v-for="(item,index) in findList"
        :key="index"
      >
        <div>
          <img :src="item.useruuid" class="ic_tou" />
          <div>
            <div>{{item.username}}</div>
            <div class="talkTime">最后聊天时间：{{item.lasttime}}</div>
          </div>
        </div>
        <div class="list_item_right">
          <div class="friends_num" v-if="item.unreadCount!=0">{{item.unreadCount}}</div>
          <img src="../assets/ic_next.png" style="width:9px;header:15px;" />
        </div>
      </div>
    </div>
    <div class="mask" v-if="isMask"></div>
    <img src="../assets/ic_pipei.png" @click="openMask()" class="pipieIcon" alt />
    <popup v-model="isMask" position="top">
      <div style="background:#fff;  padding-bottom: 16px;">
        <div class="matching_wrap">
          <div class="matching_item">
            <img
              src="../assets/ic_sex_default.png"
              @click="changeMatching(0)"
              alt
              v-if="matchIndex!=0"
            />
            <img src="../assets/ic_sexEd.png" @click="changeMatching(0)" alt v-else />
            <div>完全随机</div>
          </div>

          <div class="matching_item">
            <img
              src="../assets/ic_sex_default.png"
              @click="changeMatching(1)"
              alt
              v-if="matchIndex!=1&&userInfo.commonVip==0"
            />
            <img
              src="../assets/ic_sexEd.png"
              @click="changeMatching(1)"
              alt
              v-if="matchIndex==1&&userInfo.commonVip==0"
            />
            <!-- <img src="../assets/ic_sex_default.png" alt v-if="!userInfo.commonVip==0&&matchIndex!=1" /> -->
            <div>异性匹配(VIP)</div>
          </div>

          <div class="matching_item">
            <img
              src="../assets/ic_sex_default.png"
              @click="changeMatching(2)"
              alt
              v-if="matchIndex!=2&&userInfo.superVip==0"
            />
            <img
              src="../assets/ic_sexEd.png"
              @click="changeMatching(2)"
              alt
              v-if="matchIndex==2&&userInfo.superVip==0"
            />
            <!-- <img src="../assets/ic_sex_default.png" alt v-if="!userInfo.superVip==0&&matchIndex!=2" /> -->
            <div class="ban"></div>
            <div>异性同城(SVIP)</div>
          </div>
        </div>
        <div class="matchingBtn" @click="matchingBegin">匹配</div>
      </div>
    </popup>
    <tabbar selected="Message"></tabbar>
  </div>
</template>
<script>
import { Popup, Radio, Group, ConfirmPlugin, XSwitch } from "vux";
import tim from "@/utils/tim.js";
import TIM from "tim-js-sdk";
import * as API from "@/http/common/api";
import Tabbar from "./tab/tab";
import Vue from "vue";
import wx from "weixin-js-sdk";
export default {
  name: "messages",
  data() {
    return {
      userInfo: null,
      isMask: false,
      matchIndex: 0,
      longitude: 0, //经度
      latitude: 0, //纬度
      city: "",
      flag: localStorage.getItem("flag"),
      userInfo: {
        commonVip: "1",
        superVip: "1"
      },
      isFil: false,
      isSDK_READY: false,
      findList: [] //会话列表
    };
  },
  // created() {
  //   this.$http(API.myHomeMessage, {
  //     type: "GET",
  //     params: {
  //       userId:13
  //     }
  //   })
  //     .then(res => {
  //       if (res.data.code == 0) {
  //         this.$router.push({ name: "Tab", params: {} });
  //       }
  //     })

  // },
  watch: {
    flag(val) {
      console.log("==========", val);
    },
    deep: true,
    immediate: true
  },
  methods: {
    //去聊天
    goChat(index) {
      this.$http(API.myMessage, {
        type: "GET",
        params: {
          userId: this.findList[index].friendid
        }
      }).then(res => {
        if (res.data.code == 0) {
          this.$router.push({
            name: "Talking",
            params: { message: res.data.Message,back:false }
          });
        }
      });
    },

    changeMatching(e) {
      this.matchIndex = e;
    },
    openMask(e) {
      this.isMask = true;
    },
    // 匹配
    matchingBegin() {
      let data = this.userInfo;
      if (this.matchIndex == 0) {
        //完全匹配
        var api = API.Matching;
      }

      if (this.matchIndex == 1) {
        //vip匹配
        var api = API.vipMatching;
      }
      if (this.matchIndex == 2) {
        //svip匹配
        var api = API.svipMatching;
      }

      this.$http(api, {
        type: "POST",
        params: data
      }).then(res => {
        if (res.data.code == 0) {
          this.$router.push({
            name: "Talking",
            params: { message: res.data.Message,back:true }
          });
        } else {
          this.$vux.toast.show({ text: "网络错误，请重试", type: "text" });
        }
      });
      this.isMask = false;
    },
    // 对话列表
    getFindList() {
      var that = this;
      let data = this.userInfo.userId;
      this.$http(API.find, {
        type: "GET",
        params: {
          userId: this.userInfo.userId
        }
      }).then(res => {
        if (res.data.code == 0) {
          var a = res.data.Message;
          for (var i in a) {
            a[i].unreadCount = 0;
          }
          this.findList = a;
          setTimeout(res => {
            that.getChatList(); // 会话列表 里的 未读
          }, 2000);
        }
      });
      this.isMask = false;
      // 拉取会话列表
      // let promise = tim.getConversationList();
      // promise.then(function(imResponse) {
      //   console.log('会话列表===',imResponse)
      //   // const conversationList = imResponse.data.conversationList; // 会话列表，用该列表覆盖原有的会话列表

      // }).catch(function(imError) {
      //   console.warn('获取会话列表失败的相关信息 error:', imError); // 获取会话列表失败的相关信息
      // });
    },

    // 删除对话列表
    deleteList() {
      let data = this.userInfo.userId;
      const _this = this; // 需要注意 onCancel 和 onConfirm 的 this 指向
      this.$vux.confirm.show({
        // 组件除show外的属性
        content: "确认要删除聊天列表吗？",
        onCancel() {},
        onConfirm() {
          _this
            .$http(API.DELETE, {
              type: "POST",
              params: {
                userId: _this.userInfo.userId
              }
            })
            .then(res => {
              if (res.data.code == 0) {
                _this.findList = [];
              }
            });
        }
      });
    },
    getMessage() {
      this.$http(API.myMessage, {
        type: "GET",
        params: {
          userId: this.userInfo.userId
        }
      }).then(res => {
        if (res.data.code == 0) {
          this.userInfo = res.data.Message;
        }
      });
    },
    // 过滤器
    findallSensitiveWord() {
      this.$http(API.findallSensitiveWord, {
        type: "POST",
        params: {}
      }).then(res => {
        if (res.data.code == 0) {
          this.$localStorage.set(
            "filterText",
            JSON.stringify(res.data.message)
          );
        }
      });
    },


    //// 拉取会话列表
    getChatList() {
      var that = this;
      let promise = tim.getConversationList();
      promise
        .then(function(imResponse) {
          for (var i = 0; i < that.findList.length; i++) {
            for (var j = 0; j < imResponse.data.conversationList.length; j++) {
              if (
                that.findList[i].friendid ==
                imResponse.data.conversationList[j].userProfile.userID
              ) {
                that.findList[i].unreadCount =
                  imResponse.data.conversationList[j].unreadCount;
              }
            }
          }
          console.log("会话列表，====", imResponse.data.conversationList);
        })
        .catch(function(imError) {
          console.warn("getConversationList error:", imError); // 获取会话列表失败的相关信息
        });
    },
    //获取定位
    getCity() {
      var that = this;
      this.$http(API.getShareData, {
        type: "GET",
        params: {
          url: "http://www.xiaozounihao.club/index.html"
        }
      }).then(res => {
        wx.config({
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: "wx554b0a1adc8cc19c", // 必填，公众号的唯一标识
          timestamp: res.data.timestamp, // 必填，生成签名的时间戳
          nonceStr: res.data.nonceStr, // 必填，生成签名的随机串
          signature: res.data.signature, // 必填，签名，见附录1
          jsApiList: ["getLocation"]
        });
        wx.ready(function(res) {
          console.log(res);
          wx.getLocation({
            type: "gcj02",
            success: function(res) {
              console.log("位置++++", res);
              this.latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
              this.longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
              that.getWxCity(res.latitude, res.longitude);
            },
            cancel: function(res) {
              console.log("查看附件机器，首先要授权位置信息", res);
            },
            fail: function(res) {
              console.info("ready getLocation fail=" + JSON.stringify(res));
            }
          });
        });
      });
    },
    getWxCity(lat, lng) {
      var that = this;
      this.$http(API.dizhi, {
        type: "POST",
        params: {
          lat: lat + "",
          lng: lng + ""
        }
      }).then(res => {
        if (res.data.code == 0) {
          that.city = res.data.message.city;
          that.$localStorage.set("city", res.data.message.city);
        } else {
          this.$vux.toast.show({
            text: res.data.msg,
            type: "text"
          });
        }
      });
    }
  },
  //离开当前页
  destroyed: function() {
    this.$localStorage.set("isFil", this.isFil);
  },

  mounted() {
    var that = this;
    this.userInfo = JSON.parse(this.$localStorage.get("userInfo"));
    this.getFindList();
    this.getMessage();
    this.findallSensitiveWord();
    if (this.$localStorage.get("isFil")) {
      setTimeout(res => {
        this.isFil = this.$localStorage.get("isFil") == "true" ? true : false;
      }, 30);
    }
    if (!this.$localStorage.get("city")) {
      
      this.getCity(); //定位城市
    } else {
      this.city = this.$localStorage.get("city");
    }
    // 登录成功后会触发 SDK_READY 事件，该事件触发后，可正常使用 SDK 接口
    tim.on(TIM.EVENT.SDK_READY, this.onReadyStateUpdate, this);
    // SDK NOT READT
    tim.on(TIM.EVENT.SDK_NOT_READY, this.onReadyStateUpdate, this);

    tim.on(TIM.EVENT.MESSAGE_RECEIVED, function(event) {
      console.log("收到单聊更新通知=", event);
      if (!that.isSDK_READY) {
        let onSdkNotReady = function(event) {
          // 如果想使用发送消息等功能，接入侧需驱动 SDK 进入 ready 状态，重新调用 login 接口即可，如下所示：
          tim.login({
            userID: that.userInfo.userId + "",
            userSig: that.$localStorage.get("userSig")
          });
        };
        tim.on(TIM.EVENT.SDK_NOT_READY, onSdkNotReady);
      }
      that.getFindList(); //接受到新消息时 刷新列表
      // 收到推送的单聊、群聊、群提示、群系统通知的新消息，可通过遍历 event.data 获取消息列表数据并渲染到页面
      // event.name - TIM.EVENT.MESSAGE_RECEIVED
      // event.data - 存储 Message 对象的数组 - [Message]
    });
    // 监听事件，如：
    tim.on(TIM.EVENT.SDK_READY, function(event) {
      that.isSDK_READY = true;
      console.log("SDK_READY,监听==", event);
      // 收到离线消息和会话列表同步完毕通知，接入侧可以调用 sendMessage 等需要鉴权的接口
      // event.name - TIM.EVENT.SDK_READY
    });
    tim.on(TIM.EVENT.SDK_NOT_READY, function(event) {
      console.log("not ready 状态通知，此时 SDK 无法正常工作", event);
      // 收到 SDK 进入 not ready 状态通知，此时 SDK 无法正常工作
      // event.name - TIM.EVENT.SDK_NOT_READY
    });
  },

  components: {
    Popup,
    Radio,
    Group,
    Tabbar,
    ConfirmPlugin,
    XSwitch
  }
};
</script>
<style  scoped >
@import "../theme.less";
.noList {
  text-align: center;
  color: #666;
}
.noList > img {
  width: 150px;
  height: 150px;
  margin: 0 auto;
  margin-top: 100px;
}
.box_wrap {
  padding-bottom: 80px;
}
.mask {
  position: fixed;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.7);
  z-index: 99;
  left: 0;
  top: 0;
}
.header {
  display: flex;
  justify-content: space-between;
  height: 40px;
  background: #fff;
  align-items: center;
  padding: 0 6px 0 15px;
  box-sizing: border-box;
  border-top: 1px solid #eee;
  margin-bottom: 5px;
}
.header_left {
  display: flex;
  align-items: center;
  font-size: 12px;
}
.header_left > img {
  width: 12px;
  height: 15px;
  margin-right: 5px;
}
.header_right {
  display: flex;
  align-items: center;
  font-size: 12px;
  margin-right: 10px;
}
/*  */
.friends_warp {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 60px;
  padding: 0 13px 0 15px;
  box-sizing: border-box;
  background: #fff;
  font-size: 15px;
}
.friends_warp > div {
  display: flex;
  align-items: center;
}
.friends_num {
  width: 15px;
  height: 15px;
  border-radius: 25px;
  line-height: 15px;
  font-size: 10px;
  color: #fff;
  background: rgb(250, 0, 0);
  margin-right: 10px;
  text-align: center;
}
.talk_warp {
  display: flex;
  justify-content: space-between;
  background: #fff;
  padding: 0 13px 0 15px;
  height: 40px;
  line-height: 40px;
  align-items: center;
  margin-top: 5px;
  font-size: 13px;
}
.ic_tou {
  width: 39px;
  height: 39px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 8px;
}
.list_wrap {
  margin-top: 5px;
  padding-bottom: 60px;
}
.list_item {
  display: flex;
  height: 60px;
  font-size: 15px;
  font-weight: 500;
  color: #333333;
  align-items: center;
  justify-content: space-between;
  padding: 0 13px 0 15px;
  background: #fff;
  border-bottom: 1px solid #eee;
}
.list_item:last-child {
  border: none;
}
.list_item > div {
  display: flex;
  align-items: center;
  box-sizing: border-box;
}

.talkTime {
  font-size: 12px;
  color: #999;
}

.pipieIcon {
  width: 55.5px;
  height: 55.5px;
  position: fixed;
  right: 13.5px;
  bottom: 96px;
}
.matching_wrap {
  display: flex;
  background: #fff;
  justify-content: space-around;
}
.matching_item {
  display: flex;
  justify-content: center;
  font-size: 13px;
  margin-top: 17px;
  width: 76px;
}
.matching_item > img {
  width: 14px;
  height: 14px;
  margin: 3px 5px 0 0;
}

.matchingBtn {
  width: 240px;
  border: #e83263 solid 1px;
  border-radius: 5px;
  color: #e83263;
  text-align: center;
  line-height: 40px;
  height: 40px;
  font-size: 15px;
  margin: 0 auto;
  margin-top: 20px;
}
.del_warp {
  display: flex;
  justify-content: space-between;
  background: #fff;
  font-size: 13px;
  padding: 0 15px;
  height: 40px;
  align-items: center;
}
.del_warp > img {
  width: 14px;
  height: 14px;
}
.weui-label {
  font-size: 10px !important;
}
.vux-x-switch.weui-cell_switch {
  padding-top: 0;
  padding-bottom: 0;
}
.wrap /deep/ .vux-no-group-title {
  margin: 0 !important;
}
.wrap /deep/ .weui-cell {
  padding: 0;
}
.wrap /deep/ .weui-cells {
  font-size: 2px !important;
  margin: 0px !important;
}

.weui-cells:before {
  border: none;
}
.weui-cells:after {
  border: none;
}
.weui-switch,
.weui-switch-cp__box {
  width: 50px;
}
</style>